using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CmareaFollowObject : MonoBehaviour
{
    [Header("----- Flip Rotation -----")]
    [SerializeField] private float flipYRotationTime = .5f;
    private Player player;
    private Transform platerTrans;

    private bool isFacingRight;
    private void OnEnable()
    {
        EventCenter.AddEventListener(EventName.Camera_FollowTarget, CallTurn);
    }
    private void OnDisable()
    {
        EventCenter.RemoveEventListener(EventName.Camera_FollowTarget, CallTurn);
    }
    private void Start()
    {
        player = Player.Instance;
        platerTrans = player.transform;
    }

    private void Update()
    {
        transform.position = platerTrans.position;
    }
    public void CallTurn()
    {
        StartCoroutine(FlipYLerpCo());
    }

    private IEnumerator FlipYLerpCo()
    {
        float startRotation = transform.localEulerAngles.y;
        float endRotation = DetermineEndRotation();
        float yRotation;
        float elapsedTime = 0;

        while (elapsedTime < flipYRotationTime)
        {
            elapsedTime += Time.deltaTime;

            yRotation = Mathf.Lerp(startRotation, endRotation, elapsedTime / flipYRotationTime);
            transform.rotation = Quaternion.Euler(0, yRotation, 0);

            yield return null;
        }
    }

    private float DetermineEndRotation()
    {
        isFacingRight = !isFacingRight;

        return isFacingRight ? 180f : 0f;
    }
}
